import store from '@/store'
import router from '@/router';
import http from './fetch';
import Vue from 'vue';


/**
 * @desc 毫秒数转时间 (日D 时H 分m 秒s 毫秒S)
 * @param {number} number 要转换的毫秒数
 * @param {string} format 转换的格式
 * @param {string} unit 变量前符号 如：当unit = '\\\$'，format中 $H表示小时（1） $HH 表示小时（01）
 * @return String
 * */
function numberToTime(number, format = 'HH:mm:ss', unit = '') {
  number = isNaN(number) ? 0 : number * 1;
  let regs = {
    S: number | 0,
    s: number / 1000 | 0,
    m: number / 1000 / 60 | 0,
    H: number / 1000 / 60 / 60 | 0,
    D: number / 1000 / 60 / 60 / 24 | 0,
  };
  // 保留要输出的最高位 如：防止 format = 'mm:ss' 时 '60:00' 变为 '00:00'
  if (format.indexOf('s') >= 0) regs.S %= 1000;
  if (format.indexOf('m') >= 0) regs.s %= 60;
  if (format.indexOf('H') >= 0) regs.m %= 60;
  if (format.indexOf('D') >= 0) regs.H %= 24;

  const REG = new RegExp(unit + '[sSmHD]+', 'g');
  format = format.replace(REG, e => {
    e = e.replace('$', '');
    let val = regs[e[0]] || 0;
    val += '';
    if (e.length === 2 && val.length < 2) {
      return e.indexOf('S') < 0 ? '0' + val : val.slice(0, 2);
    } else {
      return val;
    }
  });
  return format;
}

/**
 * base64图片转File对象
 * baseStr: 图片base64编码
 * filename: 转换后文件名，true:生成随机名字
 * */

function base2img(baseStr, filename = true) {
  let arr = baseStr.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  filename === true && (filename = `file_${(Math.random() * 9999) | 0}.${mime.split('/')[1]}`);
  return new File([u8arr], filename, {type: mime});
}

/**
 * 图片文件转base64
 * file: 要编码的图片
 * return: Promise
 * */

function img2base(file) {
  return new Promise((res, req) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = r => {
      res(r.target.result);
    };
  });
}

/**
 * 图片路径转base64 (PC)
 * src: 要编码的图片路径
 * return: Promise
 * */

function imgUrl2base(src) {
  return new Promise((res, req) => {
    let canvas = document.createElement('canvas');
    let img = new Image();
    // img.setAttribute('crossOrigin', 'Anonymous');
    let ctx = canvas.getContext('2d');
    img.onload = e => {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0, img.width, img.height);
      res(canvas.toDataURL());
    };
    img.onerror = err => {
      req({code: 400, msg: err.message});
    };
    img.src = src;
  });
}

/**

 * 10位时间戳转化为年 月 日 时 分 秒

 * number: 传入时间戳

 * format：返回格式

 */

function formatTime(number, format = 'Y-MM-DD HH:mm:ss') {
  let date = number instanceof Date ? number : !isNaN(number) ? new Date(number * 1000) : false;
  if (date === false) {
    return '————';
  }

  let regs = {
    'Y': date.getFullYear(),
    'M': date.getMonth() + 1,
    'D': date.getDate(),
    'd': ['日', '一', '二', '三', '四', '五', '六'][date.getDay()],
    'H': date.getHours(),
    'm': date.getMinutes(),
    's': date.getSeconds(),
  };

  format = format.replace(/[ymdhs]+/ig, e => {
    let val = regs[e[0]];
    if (e.length === 2 && e[0] !== 'd') {
      return ('00' + val).slice(-2);
    } else {
      return val;
    }
  });

  return format;

}

/**
 * 检查是否为文件
 * params file 文件
 */

function isFileType(file) {
  const isFile = /\.((xls|doc|ppt)x?|pdf)$/i.test(file.name);
  const isType = /^((image\/(jpeg|png|gif))|(application\/(zip|pdf))|(audio\/(mp3|mpeg))|video\/mp4)$/i.test(file.type);
  return isFile || isType;
}

/**
 * 检查openid是否绑定设备
 * params file 文件
 */

function checkOpenId(callback) {
  if (!store.getters.wxUserInfo.openid) {
    return router.replace({
      name: 'Binding',
      params: {
        type: 'device'
      },
    });
  }
  callback = callback || new Function();
  http.$post('webcat/api/get_uid', {
    openid: store.getters.wxUserInfo.openid,
  }).then(res => {
    if (res.uid) {
    // if (res.uid && res.device_tokens) {
      getUserInfoApi(res.uid).then(callback).catch(console.log);
    } else {
      store.commit('setUserInfo', {});
      router.replace({
        name: 'Binding',
        params: {
          type: 'device'
        },
      });
    }
  }).catch(http.$err);
}

/**
 * 检查微信授权
 * fullPath 获取微信授权后跳转路径
 */

async function checkWxToken(fullPath) {
  if (store.state.wxUserInfo.openid) return store.getters.wxUserInfo;
  let _params = {};
  // get url query
  let queryArr = location.search.slice(1);
  if (queryArr) {
    queryArr = queryArr.split('&');
  }
  let query = {};
  queryArr && queryArr.map(e => {
    let arr = e.split('=');
    query[arr[0]] = decodeURIComponent(arr[1]);
  });

  // check code
  // alert('query:::' + JSON.stringify(query));
  let wx_code = query.code;
  let state = query.state;
  // alert('wx_code:::' + wx_code);
  fullPath = encodeURIComponent(fullPath);
  if (!state) {
    router.replace("/auth?path=" + fullPath);
    throw 'auth';
  } else if (!wx_code) {
    router.go(-1);
    throw 'cancel';
  } else {
    try {
      let res = await http.$post('webcat/api/get_wx_info', {
        code: wx_code,
      });
      _params.nickname = res.nickname;
      res.nickname = '\\u' + res.nickname.split('').map(s => ('0000' + s.charCodeAt().toString(16)).slice(-4)).join('\\u');
      _params.realname = res.nickname;
      _params.unionid = res.unionid;
      _params.openid = res.openid;
      _params.icon = res.headimgurl;
      _params.uid = res.uid || '';
      _params.is_register = res.is_register || false;
      _params.content = JSON.stringify(res);
      store.commit('setWxUserInfo', _params);
      return store.getters.wxUserInfo;
    } catch (err) {
      if (err.code && (err.code * 1 !== 201)) {
        router.replace('/auth?path=' + fullPath);
        throw 'auth';
      } else {
        throw err;
      }
    }
  }
}

/**
 * 登录
 * uid 邀请人uid， 有值则为分销注册
 * fullPath 获取微信授权后跳转路径
 * */
async function login(uid = '', fullPath = '') {
  // if (store.state.isLogin) return 'isLogin';
  // store.commit('setIsLogin', true);deviceToken
  try {
    let {wxUserInfo, productInfo, turing: {device_token}} = store.getters;
    // console.log(wxUserInfo);
    // device_token = 'Ag50cIcTejw4AKuOqOmFHfoHbMJagQ2w7XoobbSIG6iy';
    if (!wxUserInfo.openid) {
      await checkWxToken(fullPath);
    }
    let {openid, unionid, realname, icon, content} = store.getters.wxUserInfo;
    let res = await http.$post('webcat/api/bind_wx', {
      openid,
      unionid,
      device_tokens: device_token,
      third_id: 1,
      content,
      uid,
    });
    store.commit('setIsLogin', false);
    return await getUserInfoApi(uid);
  } catch (e) {
    store.commit('setIsLogin', false);
    throw e;
  }
}

/**
 * 设置微信js-sdk config
 * */

function setWxConfig(jsApiList = [], url = location.href.split('#')[0]) {
  jsApiList = [
    ...jsApiList,
    // 'updateAppMessageShareData',
    // 'updateTimelineShareData',
    // 'onMenuShareTimeline', // 旧的接口，即将废弃
    // 'onMenuShareAppMessage' // 旧的接口，即将废弃
  ];
  let params = {
    url,
    // product_id: 0 //
  };
  return http.$post('webcat/api/get_sign', params).then(res => {
    res = res.sign;
    let wxConfig = {
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: res.app_id, // 必填，公众号的唯一标识
      timestamp: res.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.noncestr, // 必填，生成签名的随机串
      signature: res.sign, // 必填，签名
      jsApiList // 必填，需要使用的JS接口列表
    };
    wx.config(wxConfig);
    return res;
  });
}

/**
 * 检查是否可以使用指定js-sdk
 * */

function checkJsApi(jsApiList) {
  if (typeof jsApiList === 'string') {
    jsApiList = [jsApiList];
  }
  return new Promise((res, req) => {
    wx.checkJsApi({
      jsApiList, // 需要检测的JS接口列表，所有JS接口列表见附录2,
      success(r) {
        // 以键值对的形式返回，可用的api值true，不可用为false
        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
        alert(JSON.stringify(jsApiList) + '|' + JSON.stringify(r));
        if (r.errMsg === 'checkJsApi:ok') {
          if (jsApiList.length === 1) {
            res(r.checkResult[jsApiList[0]]);
          } else {
            res(r.checkResult);
          }
        } else {
          req(r);
        }
      }
    });
  });
}

/**
 * 获取用户详情
 * */

async function getUserInfoApi(uid = store.getters.userInfo.uid, product_id = store.getters.productInfo.product_id) {
  let res = {};
  if (uid) {
    res = await http.$post('user/api/get_info', {uid, product_id});
    res.uid = res.uid || res.id;
  } else {
    store.commit('setWxUserInfo', {});
  }
  store.commit('setUserInfo', res);
  return res;
}

/**
 * 刷新页面
 * key 保存storage时使用的key
 * @return
 * */

function reload(key = 'reload') {
  if (localStorage.getItem(key)) {
    localStorage.removeItem(key);
    return false;
  } else {
    localStorage.setItem(key, '1');
    let url = location.href;
    if (!/\?(.+)?#/.test(url)) {
      url = url.replace('#', '?#');
    } else {
      url = url.replace(/(&_=\d+)?#/i, `&_=${new Date().getTime()}#`);
    }
    location.replace(url);
    return true;
  }
}

/**
 * 全局弹窗
 * */
function showPopup(options) {
  if (!options) {
    options = '';
  }
  if (typeof options === 'string') {
    options = {
      content: options,
    };
  }
  let opt = Object.assign({}, options);
  let Show = Vue.extend(require('../base/glpopup').default);
  let show = new Show({el: document.createElement('div')});
  if (typeof opt.sure === 'function') {
    show.$on('sure', opt.sure);
  } else {
    show.$on('sure', e => e());
  }
  if (typeof opt.close === 'function') {
    show.$on('close', opt.close);
  }
  delete opt.sure;
  delete opt.close;
  Object.assign(show, opt);
  document.body.appendChild(show.$el);
}


/**
 * 全局选择器
 * */
function picker(options) {
  if (!options) {
    options = [];
  }
  if (Array.isArray(options)) {
    options = {
      columns: options,
    };
  }
  let opt = Object.assign({}, options);
  let Show = Vue.extend(require('../base/glselect').default);
  let show = new Show({el: document.createElement('div')});
  if (typeof opt.sure === 'function') {
    show.$on('sure', opt.sure);
  }
  if (typeof opt.change === 'function') {
    show.$on('change', opt.change);
  }
  delete opt.sure;
  delete opt.change;
  Object.assign(show, opt);
  document.body.appendChild(show.$el);
}

module.exports = {
  numberToTime,
  formatTime,
  isFileType,
  base2img,
  img2base,
  imgUrl2base,
  checkWxToken,
  checkOpenId,
  login,
  setWxConfig,
  checkJsApi,
  getUserInfoApi,
  reload,
  showPopup,
  picker,
};
